package com.chenyun.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import cn.hutool.crypto.digest.DigestUtil;
import com.chenyun.common.annotation.Log;
import com.chenyun.common.enums.operlog.BusinessTypeEnum;
import com.chenyun.system.model.SysRole;
import com.chenyun.system.model.SysUser;
import com.chenyun.system.service.ISysPermissionService;
import com.chenyun.system.service.ISysPostService;
import com.chenyun.system.service.ISysRoleService;
import com.chenyun.system.service.ISysUserService;
import com.chenyun.boot.web.controller.BaseController;
import com.chenyun.common.constants.UserConstants;
import com.chenyun.common.utils.StringUtils;
import com.chenyun.common.vo.AjaxResult;
import com.chenyun.common.vo.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/user")
@Api(tags = "平台端管理员信息-admin")
public class SysUserController extends BaseController<ISysUserService, SysUser> {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;


    @ApiOperation("获取用户列表")
    @SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public PageResult list(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        Long userId = Convert.toLong(getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);

        SysUser sysUser = userService.selectUserById(userId);
        AjaxResult ajax = AjaxResult.SUCCESS(new HashMap<String, Object>() {{
            put("userInfo", sysUser);
            put("menuPermission", permissions);
            put("roles", roles);
        }});
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户编号获取详细信息")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        HashMap<String, Object> map = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        map.put("posts", postService.selectPostAll());
        if (Objects.nonNull(userId)) {
            map.put("info", userService.selectUserById(userId));
            map.put("postIds", postService.selectPostListByUserId(userId));
            map.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return toAjax(map);
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PostMapping
    @Log(title = "新增用户", businessType = BusinessTypeEnum.INSERT, desc = "'新增用户['+#user.getUserName()+']'")
    @SaCheckPermission("system:user:add")
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.FAIL("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.FAIL("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.FAIL("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @PostMapping("edit")
    @Log(title = "修改用户", businessType = BusinessTypeEnum.UPDATE, desc = "'修改用户['+#user.getUserId()+']'")
    @SaCheckPermission("system:user:edit")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.FAIL("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.FAIL("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
//        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @PostMapping("del")
    @Log(title = "删除用户", businessType = BusinessTypeEnum.DELETE, desc = "'删除用户'")
    @SaCheckPermission("system:user:del")
    public AjaxResult remove(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return AjaxResult.FAIL("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PostMapping("/resetPwd")
    @Log(title = "重置用户密码", businessType = BusinessTypeEnum.UPDATE, desc = "'重置用户['+#user.getUserId()+']密码'")
    @SaCheckPermission("system:user:resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(DigestUtil.sha1Hex(user.getPassword()));
//        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PostMapping("/changeStatus")
    @Log(title = "修改用户状态", businessType = BusinessTypeEnum.UPDATE, desc = "'修改用户状态['+#user.getUserId()+']'")
    @SaCheckPermission("system:user:editStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
//        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @ApiOperation("根据用户编号获取授权角色")
    @GetMapping("/authRole/{userId}")
    @SaCheckPermission("system:user:roles")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {

        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        return AjaxResult.SUCCESS(new HashMap<String, Object>() {{
            put("user", user);
            put("roles", roles);
        }});

    }

    /**
     * 用户授权角色
     */
    @ApiOperation("用户授权角色")
    @PostMapping("/authRole")
    @Log(title = "为用户设置角色组", businessType = BusinessTypeEnum.INSERT, desc = "'用户编号['+#userId+']'")
    @SaCheckPermission("system:user:authRole")
    public AjaxResult insertAuthRole(Long userId, @RequestBody Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }
}
